package com.bookstore.filter;

import com.bookstore.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        String filters = config.getInitParameter("filters");
        String filterName = config.getFilterName();
        System.out.println(filterName);
        System.out.println(filters);
        ServletContext servletContext = config.getServletContext();
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        User user = (User) req.getSession().getAttribute("user");
        if(user!=null){
            chain.doFilter(request,response);
        }else {
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }
    }
}
